<template>
  <div class="exercise-container">
    <h2 class="page-title">
      未做练习
    </h2>

    <!-- 加载状态 -->
    <div
      v-if="loading"
      class="loading"
    >
      加载中...
    </div>

    <!-- 错误提示 -->
    <div
      v-if="error"
      class="error"
    >
      {{ error }}
    </div>

    <!-- 练习列表 -->
    <div
      v-else-if="!currentExercise"
      class="exercise-grid grid gap-4"
    >
      <div
        v-for="exercise in exercises"
        :key="exercise.exerciseId"
        class="exercise-card flex-shrink-0"
      >
        <div class="card-body">
          <h5 class="card-title">
            {{ exercise.exerciseName }}
          </h5>
          <p class="card-text">
            总分：{{ exercise.exerciseScore }}分<br>
            <!-- 添加开始时间显示 -->
            开始时间：{{ formatTime(exercise.startTime) }}<br>
            截止时间：{{ formatTime(exercise.deadline) }}
            <!-- 新增：显示截止状态 -->
            <span 
              v-if="isExerciseExpired(exercise.deadline)" 
              class="text-red-500 ml-2"
            >
              (已截止)
            </span>
            <!-- 新增：显示未开始状态 -->
            <span 
              v-else-if="isExerciseNotStarted(exercise.startTime)" 
              class="text-yellow-600 ml-2"
            >
              (未开始)
            </span>
          </p>
          <div class="text-end">
            <!-- 修改：添加disabled属性和不同样式 -->
            <button 
              class="btn"
              :class="{
                'btn-primary': canStartExercise(exercise),
                'btn-gray-300 text-gray-500 cursor-not-allowed': 
                  !canStartExercise(exercise)
              }"
              :disabled="!canStartExercise(exercise)"
              @click="canStartExercise(exercise) ? handleExerciseClick(exercise) : null"
            >
              {{ getButtonText(exercise) }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 练习详情 -->
    <ExerciseDetail
      v-else
      :exercise="currentExercise"
      @back="handleBack"
      @submit="handleSubmit"
    />

    <!-- 返回按钮 -->
    <button
      v-if="currentExercise"
      type="button"
      class="btn btn-secondary mt-4"
      @click="handleBack"
    >
      <i class="fa fa-chevron-left me-1" /> 返回练习列表
    </button>
  </div>
</template>

<script>
import ExerciseDetail from './ExerciseDetail.vue';
import axios from 'axios';

export default {
  components: { ExerciseDetail },
  props: {
    userId: {
      type: String,
      required: true
    },
    courseId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      currentExercise: null,
      exercises: [],
      loading: true,
      error: null
    };
  },
  mounted() {
    this.fetchUnfinishedExercises();
  },
  methods: {
    // 格式化时间显示
    formatTime(timestamp) {
      if (!timestamp) return '未知时间';
      const date = new Date(timestamp);
      return `${date.getFullYear()}/${(date.getMonth() + 1).toString().padStart(2, '0')}/${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },
    
    // 判断练习是否未开始
    isExerciseNotStarted(startTime) {
      if (!startTime) return false;
      const current = new Date();
      const start = new Date(startTime);
      return current < start;
    },
    
    // 新增：判断练习是否可以开始
    canStartExercise(exercise) {
      const current = new Date();
      
      // 未开始的情况
      if (this.isExerciseNotStarted(exercise.startTime)) {
        return false;
      }
      
      // 已截止的情况
      if (this.isExerciseExpired(exercise.deadline)) {
        return false;
      }
      
      return true;
    },
    
    // 新增：获取按钮显示文本
    getButtonText(exercise) {
      if (this.isExerciseNotStarted(exercise.startTime)) {
        return '练习未开始';
      } else if (this.isExerciseExpired(exercise.deadline)) {
        return '已截止';
      } else {
        return '开始练习';
      }
    },

    // 判断练习是否已过期
    isExerciseExpired(deadline) {
      if (!deadline) return false; // 如果没有截止时间，默认不过期
      const currentTime = new Date();
      const deadlineTime = new Date(deadline);
      return currentTime > deadlineTime;
    },

    async fetchUnfinishedExercises() {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.get('/api/exercises/unfinished', {
          params: { userId: this.userId, courseId: this.courseId }
        });
        if (response.data && Array.isArray(response.data)) {
          this.exercises = response.data.map(exercise => ({
            exerciseId: exercise.exerciseId,
            exerciseName: exercise.exerciseName,
            exerciseScore: exercise.exerciseScore,
            deadline: exercise.exerciseDeadline,
            // 新增：添加开始时间
            startTime: exercise.exerciseStartTime
          }));
        } else {
          this.error = '未获取到未完成练习列表';
          console.error('后端返回数据格式错误:', response.data);
        }
      } catch (err) {
        this.error = '加载练习列表失败，请重试';
        console.error('接口请求失败:', err);
      } finally {
        this.loading = false;
      }
    },

    async handleExerciseClick(exercise) {
      // 如果练习未开始或已过期，不执行任何操作
      if (!this.canStartExercise(exercise)) {
        return;
      }
      
      try {
        // 并行获取练习信息和题目列表
        const [exerciseInfo, questions] = await Promise.all([
          axios.get(`/api/exercises/${exercise.exerciseId}`),
          axios.get(`/api/exercises/${exercise.exerciseId}/questions`)
        ]);

        // 处理题目数据，分离题目内容和选项
        const processedQuestions = questions.data.map(question => {
          const { questionId, questionContent, type, questionScore, questionAnswer } = question;
          
          // 先将 \\n 还原为 \n
          const unescapedContent = questionContent.replace(/\\n/g, '\n');
          
          // 选择题处理
          if (type === false) {
            const lines = unescapedContent.split('\n');
            const options = [];
            let contentLines = [];
            let optionsStarted = false;
            
            // 逐行检查，分离题目和选项
            lines.forEach(line => {
              const optionMatch = /^([A-Z])\.\s*(.+)$/.exec(line);
              
              if (optionMatch && !optionsStarted) {
                optionsStarted = true;
              }
              
              if (optionsStarted && optionMatch) {
                options.push({
                  key: optionMatch[1],
                  text: optionMatch[2]
                });
              } else {
                contentLines.push(line);
              }
            });
            
            return {
         id: questionId,
              content: contentLines.join('\n').trim(),
              type,
              score: questionScore,
              options,
              answer: questionAnswer
            };
          }
          
          // 主观题直接返回
          return {
            id: questionId,
            content: unescapedContent,
            type,
            score: questionScore,
            options: [],
            answer: questionAnswer
          };
        });

        // 更新练习列表中的题目数量
        this.exercises = this.exercises.map(e => 
          e.exerciseId === exercise.exerciseId 
            ? { ...e, questionCount: processedQuestions.length } 
            : e
        );

        // 设置当前练习详情
        this.currentExercise = {
          ...exerciseInfo.data,
          deadline: exerciseInfo.data.exerciseDeadline,
          startTime: exerciseInfo.data.exerciseStartTime, // 添加开始时间
          questions: processedQuestions,
          totalScore: exerciseInfo.data.exerciseScore
        };

        console.log('处理后的题目数据:', processedQuestions);
      } catch (err) {
        this.error = '获取练习详情失败';
        console.error('获取练习详情失败:', err);
      }
    },

    handleBack() {
      this.currentExercise = null;
    },

    async handleSubmit(studentAnswers) {
      try {
        const userId = this.userId;
        const exerciseId = this.currentExercise.exerciseId;

        // 构造 studentExercise（仅需主键，无需手动设置 exercise 关联）
        const studentExercise = {
          id: {
            userId: userId,
            exerciseId: exerciseId
          },
          state: "submitted"
        };

        // 构造 studentQuestionAnswers，确保复合主键完整
        const studentQuestionAnswers = studentAnswers;

        console.log('提交的数据:', { studentExercise, studentQuestionAnswers });

        await axios.post('/api/exercises/submitted', {
          studentExercise,
          studentQuestionAnswers
        });

        alert('提交成功！');
        this.handleBack();
        this.fetchUnfinishedExercises();
      } catch (err) {
        console.error('错误响应:', err.response?.data);
        const errorMessage = err.response?.data?.message || '提交失败，请重试';
        alert(`提交失败: ${errorMessage}`);
      }
    }
  }
};
</script>

<style scoped>
/* 导入公共样式 */
@import '../../assets/css/exercise_css/ExerciseCommon.css';

/* 仅保留该组件特有的样式 */
.exercise-grid {
  margin-bottom: 0; /* 移除列表底部间距 */
}

.exercise-card {
  width: 250px; /* 固定宽度 */
}

@media (min-width: 768px) {
  .exercise-card { margin-bottom: 1.5rem; }
}

@media (min-width: 1024px) {
  .exercise-card { margin-right: 2rem; }
}

/* 新增：禁用按钮样式 */
.btn-gray-300 {
  background-color: #e2e8f0;
  border-color: #e2e8f0;
}

/* 显示状态的样式 */
.text-yellow-600 {
  color: #ca8a04;
}
</style>